package com.fengye.algorithms.alibaba.dagscheduler;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 任务的有向无环图
 * @Author fengye
 * @Date 2023/4/6 11:08
 **/
public class TaskDigraph {
    private Set<Task> tasks;
    private Map<Task, Set<Task>> edges;

    public TaskDigraph() {
        tasks = new HashSet<Task>();
        edges = new HashMap<Task,Set<Task>>();
    }

    public TaskDigraph(Set<Task> tasks, Map<Task, Set<Task>> edges) {
        this.tasks = tasks;
        this.edges = edges;
    }

    public void addTask(Task task) {
        if(task == null || tasks.contains(task)) {
            throw new IllegalArgumentException("task is null or all ready in tasks");
        }
        tasks.add(task);
    }

    public void addEdge(Task task, Task prev) {
        if(!tasks.contains(task) || !tasks.contains(prev)) {
            throw new IllegalArgumentException("task not in tasks");
        }

        Set<Task> prevs = edges.get(task);
        if(prevs == null) {
            prevs = new HashSet<Task>();
            edges.put(task, prevs);
        }

        if(prevs.contains(prev)) {
            throw new IllegalArgumentException("prev task in edges");
        }

        prevs.add(prev);
    }

    public Set<Task> getTasks() {
        return tasks;
    }

    public void setTasks(Set<Task> tasks) {
        this.tasks = tasks;
    }

    public Map<Task, Set<Task>> getEdges() {
        return edges;
    }

    public void setEdges(Map<Task, Set<Task>> edges) {
        this.edges = edges;
    }

}
